﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
namespace HB.Base
{
    public class NATHelper
    {
        public class NatModel
        {
            public string ListenIP { get; set; } = "*";
            public int ListenPort { get; set; }
            public string TargetIP { get; set; }
            public int TargetPort { get; set; }
        }
        /// <summary>
        /// 获取当前NAT列表
        /// </summary>
        /// <returns></returns>
        public static List<NatModel> GetList()
        {
            string cmd = "netsh interface portproxy show  v4tov4";
            var result = CmdHelper.ExecShellForResult(cmd);
            List<NatModel> ls = new List<NatModel>();
            var lines = result.Split(Environment.NewLine.ToCharArray());
            foreach (var line in lines.Where(zz => zz != ""))
            {
                if (Regex.IsMatch(line, @"[0-9.\* ]{43,52}"))
                {
                    var items = line.Split(' ');
                    var ps = items.Where(zz => zz != "").ToArray();
                    if (ps.Count() == 4)
                    {
                        NatModel m = new NatModel();
                        m.ListenIP = ps[0];
                        m.ListenPort = int.Parse(ps[1]);
                        m.TargetIP = ps[2];
                        m.TargetPort = int.Parse(ps[3]);
                        ls.Add(m);
                    }
                }
            }
            return ls;
        }

        /// <summary>
        /// 增加NAT，需要管理员权限
        /// </summary>
        /// <param name="model"></param>
        public static void Add(NatModel model)
        {
            string cmd = $"netsh interface portproxy add v4tov4 listenaddress={model.ListenIP} listenport={model.ListenPort} connectaddress={model.TargetIP}  connectport={model.TargetPort}";
            var file = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "NAT.bat");
            System.IO.File.WriteAllText(file, cmd);
            CmdHelper.RunProcess(file, true);
        }

        /// <summary>
        /// 删除NAT，需要管理员权限
        /// </summary>
        /// <param name="port"></param>
        /// <param name="listenIp"></param>
        public static void Delete(int port, string listenIp = "*")
        {
            string cmd = $"netsh interface portproxy delete v4tov4 listenaddress={listenIp}  listenport={port}";
            var file = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "NAT.bat");
            System.IO.File.WriteAllText(file, cmd);
            CmdHelper.RunProcess(file, true);
        }
    }
}
